<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <div class="question">{{title}}</div>
        <el-form
          :model="formdate"
          :rules="rules"
          ref="ruleForm"
          label-width="140px"
        >
          <!-- 学科 -->
          <el-form-item label="学科" prop="subjectID">
            <el-select
              placeholder="请选择"
              v-model="formdate.subjectID"
              @change="changesubject"
            >
              <el-option
                v-for="item in disciplinesdate"
                :key="item.id"
                :label="item.subjectName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!--  目录-->
          <el-form-item label="目录" prop="catalogID">
            <el-select
              placeholder="请选择"
              v-model="formdate.catalogID"
              @click.native="getdirectory"
            >
              <el-option
                v-for="item in directorydate"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业" prop="enterpriseID">
            <el-select
              placeholder="请选择"
              v-model="formdate.enterpriseID"
              :popper-append-to-body="false"
              @click.native="getenterprise"
            >
              <el-option
                v-for="item in company"
                :key="item.id"
                :label="item.shortName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市" prop="province">
            <el-select
              placeholder="请选择"
              class="city-left"
              v-model="formdate.province"
              @change="getprovince"
            >
              <el-option
                v-for="item in province"
                :key="item.city"
                :label="item.city"
                :value="item.city"
              >
              </el-option>
            </el-select>
            <!-- 县 -->
            <el-select
              placeholder="请选择"
              class="city-right"
              v-model="formdate.city"
              @click.native="getcity(formdate.province)"
            >
              <el-option
                v-for="item in citys"
                :key="item.city"
                :label="item.city"
                :value="item.city"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向" prop="direction">
            <el-select
              placeholder="请选择"
              v-model="formdate.direction"
              @click.native="getdirection"
            >
              <el-option
                v-for="item in directions"
                :key="item.direction"
                :label="item.direction"
                :value="item.direction"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型">
            <el-radio-group v-model="formdate.questionType">
              <el-radio :label="'1'">单选</el-radio>
              <el-radio :label="'2'">多选</el-radio>
              <el-radio :label="'3'">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度">
            <el-radio-group v-model="formdate.difficulty">
              <el-radio :label="'1'">简单</el-radio>
              <el-radio :label="'2'">一般</el-radio>
              <el-radio :label="'3'">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干" prop="question">
            <quill-editor
              v-model="formdate.question"
              :options="editorOption"
            ></quill-editor>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项" v-if="formdate.questionType === '1' ||formdate.questionType === '' ||formdate.questionType === '2'">
            <el-radio-group
              v-for="item in formdate.options"
              :key="item.code"
              v-model="roadio"
              @change="getoptions"
            >
              <el-radio
                :label="item.code"
                v-if="
                  formdate.questionType === '1' || formdate.questionType === ''
                "
                v-model="item.isRight"
                >{{ item.code }}</el-radio
              >

              <el-checkbox
                v-if="formdate.questionType === '2'"
                style="margin-right: 30px"
                v-model="item.isRight"
                >{{ item.code }}</el-checkbox
              >

              <el-input
                v-model="item.title"
                placeholder="请输入内容"
                class="inputbox"
              ></el-input>
          <!-- 头像 -->
              <uploadPhoto ref="reference"></uploadPhoto>

            </el-radio-group>

            <el-button
              type="danger"
              size="small"
              @click.native="addQuestion"
              v-if="formdate.questionType === '2'"
              >+增加选项与答案</el-button
            >
            <el-button
              type="danger"
              size="small"
              v-if=" formdate.questionType === '1' || formdate.questionType === ''" disabled>+增加选项与答案</el-button>
          </el-form-item>
          <!-- 视频解析 -->
          <el-form-item label="视频解析">
            <el-input v-model="formdate.videoURL"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析" prop="answer">
            <quill-editor
              v-model="formdate.answer"
              :options="editorOption"
            ></quill-editor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注">
            <el-input
              type="textarea"
              class="note"
              v-model="formdate.remarks"
            ></el-input>
          </el-form-item>
          <!-- 题目标签 -->
          <el-form-item label="题目标签">
            <el-select
              placeholder="请选择试题标签"
              v-model="formdate.tags"
              @click.native="gettags"
              filterable
              allow-create
              default-first-option
              multiple
            >
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.tagName"
                :value="item.tagName"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!--提交按钮 -->
          <el-form-item label-width="70px">
            <el-button type="primary" @click="onSubmit" v-if="title==='试题添加'" >立即提交</el-button>
            <el-button type="success" v-if="title==='试题修改'" @click="onSubmit">立即修改</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 富文本编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 城市和县的数据
import { provincess, citys } from '../../api/hmmm/citys'
// 学科的接口
import { list } from '../../api/hmmm/subjects'
// 目录，公司，标签,回显.,企业详情的接口
import { getdirectory, getenterprise, gettags, getenterpriseid } from '../../api/questions'
// 方向的数据
import { direction } from '../../api/hmmm/constants'
// 添加,获取详情，修改的接口
import { add as addquestions, detail, update } from '../../api/hmmm/questions'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      // 表格的绑定数据
      formdate: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        options: [
          {
            // 选中的A B C D
            code: 'A',
            // input中输入的每个选项
            title: '',
            // 图片url
            img: '',
            // 布尔值true或false，选的哪个选项，哪个选项就为true
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      },
      roadio: '',
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入试题标签', trigger: 'blur' }
        ]
      },
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            // [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            // [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            // [{ script: 'sub' }, { script: 'super' }], // 上下标
            // [{ indent: '-1' }, { indent: '+1' }], // 缩进
            // [{ direction: 'rtl' }], // 文本方向
            // [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            // [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            // [{ font: [] }], // 字体
            // [{ align: [] }], // 对齐方式
            // ['clean'], // 清除字体样式
            ['image', 'video'] // 上传图片、上传视频
          ]
        },
        placeholder: ''
      },
      // 存放学科的数据
      disciplinesdate: [],
      // 存放学科的数据
      directorydate: [],
      // 存放公司名称的数据
      company: [],
      // 城市
      province: provincess,
      // 县
      citys: [],
      // 存放方向的数据
      directions: [],
      // 存放标签的数据
      tags: [],
      npage: {
        page: 1,
        pagesize: 9999
      },
      i: 0,
      // 目录的id
      cata: '',
      cataname: '',
      // 企业id
      enterpriseid: '',
      // 企业名字
      enterprisename: ''
    }
  },
  computed: {
    title () {
      return this.formdate.id ? '试题修改' : '试题添加'
    }
  },
  created () {
    this.getdisciplines()
    this.getquestionnew()
  },
  methods: {
    // 获取回显的数据
    async getquestionnew () {
      const ids = this.$route.query.id
      if (!ids) return
      const res = await detail({ id: ids })
      const res1 = await getenterpriseid(res.data.enterpriseID)
      console.log(res1)
      this.enterpriseid = res1.data.id
      this.enterprisename = res1.data.company
      this.cata = res.data.catalogID
      this.cataname = res.data.directoryName
      res.data.tags = res.data.tags.split(',')
      res.data.catalogID = res.data.directoryName
      res.data.enterpriseID = res1.data.company
      this.formdate = res.data
      // console.log(res)
      if (res.data.questionType === '1') {
        for (let i = 0; i < res.data.options.length; i++) {
          if (res.data.options[i].isRight === 1) {
            this.roadio = res.data.options[i].code
          }
        }
      }
      if (res.data.questionType === '2') {
        for (let i = 0; i < res.data.options.length; i++) {
          if (res.data.options[i].isRight === 1) {
            res.data.options[i].isRight = true
          }
        }
      }

      const reference = this.$refs.reference
      for (let i = 0; i < res.data.options.length; i++) {
        if (res.data.options[i].img === '' || res.data.options[i].img === null) return
        reference[i].fileList = [{ url: res.data.options[i].img }]
      }
    },
    // 获取学科的方法
    async getdisciplines () {
      const res = await list(this.npage)
      this.disciplinesdate = res.data.items
    },
    // 获取目录方法
    async getdirectory () {
      const res = await getdirectory(this.formdate.subjectID)
      this.directorydate = res.data.items
    },
    // 当学科发生改变的时候
    changesubject () {
      this.formdate.catalogID = ''
      this.formdate.tags = ''
      this.getdirectory()
    },
    // 获取企业的方法
    async getenterprise () {
      const { data } = await getenterprise(this.page, this.pagesize)
      this.company = data.items
    },
    // 获取城市的方法
    getcity (province) {
      const city = citys(province)
      this.citys = city.map((item) => {
        return { city: item }
      })
    },
    // 当市区发生改变的时候
    getprovince () {
      this.formdate.city = ''
      this.getcity()
    },
    // 获取方向的数据
    getdirection () {
      this.directions = direction.map((item) => {
        return { direction: item }
      })
    },
    // 获取标签数据的方法
    async gettags () {
      const res = await gettags(this.formdate.subjectID)
      this.tags = res.data.items
    },
    // 清空数据
    empty () {
      this.$refs.ruleForm.resetFields()
      this.formdate = {
        subjectID: '', // 学科
        ctaalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '', // 题型
        difficulty: '', // 难度
        question: '', // 题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        options: [
          {
            // 选中的A B C D
            code: 'A',
            // input中输入的每个选项
            title: '',
            // 图片url
            img: '',
            // 布尔值true或false，选的哪个选项，哪个选项就为true
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      }
    },
    // 点击提交按钮的时候
    onSubmit () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        this.formdate.tags = this.formdate.tags.toString()

        const options = this.formdate.options
        const imgs = this.$refs.reference
        for (let i = 0; i < options.length; i++) {
          options[i].img = imgs[i].fileList[0]?.url
        }

        if (this.formdate.id) {
          if (this.formdate.catalogID === this.cataname) {
            this.formdate.catalogID = this.cata
          }
          if (this.formdate.enterpriseID === this.enterprisename) {
            this.formdate.enterpriseID = this.enterpriseid
          }
          await update(this.formdate)
          this.$message.success('恭喜修改成功')
        } else {
          const res = await addquestions(this.formdate)
          console.log(res)
          this.$message.success('恭喜添加成功')
        }
        this.empty()
        this.$router.push('/questions/list')
      })
    },
    // 随机顺序生成ABCDE...字母的函数
    setDesc () {
      const letterArr = []
      // 字母A的code值是65，但因为已经到字母D了，所以直接从69E开始循环
      for (let i = 69; i < 91; i++) {
        letterArr[i] = String.fromCharCode(i)
      }
      return letterArr
    },
    // 增加选项和答案按钮
    addQuestion () {
      // 调用随机顺序生成ABCDE...字母的函数，可以打印 randomAbc 数组看下
      // 有69个元素是空的，所以直接进行了截取
      const randomAbc = this.setDesc().splice(69)
      const res = [
        ...this.formdate.options,
        {
          code: randomAbc[this.i],
          title: '',
          img: '',
          isRight: false
        }
      ]
      this.i++
      this.formdate.options = res
    },
    // 当单选的时候改变isRightde的状态
    getoptions (val) {
      this.formdate.options = this.formdate.options.map((item) => {
        if (item.code === val) {
          item.isRight = true
        } else {
          item.isRight = false
        }
        return item
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select {
  ::v-deep .el-input__inner {
    width: 400px;
  }
}
.city-left {
  margin-right: 10px;
  ::v-deep .el-input__inner {
    // margin-right: 100px;
    width: 195px;
  }
}
.city-right {
  ::v-deep .el-input__inner {
    // margin-right: 100px;
    width: 195px;
  }
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 250px;
  }
}
.el-input {
  ::v-deep .el-input__inner {
    width: 400px;
  }
}
.el-form-item {
  ::v-deep .el-form-item__content {
    margin-left: 50px;
  }
}
.note {
  ::v-deep .el-textarea__inner {
    width: 400px;
    height: 100px;
  }
}
.el-card {
  ::v-deep .el-card__body {
    padding: 1px 1px 1px 1px;
  }
  .el-form {
    padding-top: 20px;
  }
  .question {
    // background-color: antiquewhite;
    // padding: 18px 20px;
    border-bottom: 1px solid #ebeef5;
    line-height: 50px;
    padding-left: 20px;
  }
  .el-radio-group {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 15px;
    ::v-deep .el-input {
      width: 26%;
    }
  }
}
.inputbox{
::v-deep .el-input__inner{
    width: 100% !important;
  }
}
</style>
